package com.huatai.bpmn.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huatai.bpmn.commom.emnu.StatusCode;
import com.huatai.bpmn.entity.FormEntity;
import com.huatai.bpmn.service.FormService;
import com.huatai.common.api.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  表单表
 * </p>
 *
 * @author yxy
 * @since 2023-07-07
 */
@RestController
@RequestMapping("/from")
@Api(value = "表单表", tags = "表单表")
public class FormController {
	@Autowired
	private FormService formService;



	@PostMapping(value = "/page")
	@ApiOperation(value = "表单列表 data参数为pgIndex页数，pgSize条数")
	public R page(@RequestBody JSONObject data) throws ParseException {
		IPage page = formService.page(data);
		return R.data(page);
	}

	@PostMapping(value = "/save")
	@ApiOperation(value = "表单新增")
	public R save(@Valid @RequestBody FormEntity data) {
		boolean flag = formService.save(data);
		return flag? R.success("新增成功"): R.fail("新增失败");
	}

	@PostMapping(value = "/update")
	@ApiOperation("表单修改")
	public R update(@Valid @RequestBody FormEntity data) {
		boolean flag = formService.updateById(data);
		return flag? R.success("修改成功"): R.fail("修改失败");
	}

	@DeleteMapping("/remove/{id}")
	@ApiOperation("表单删除")
	public R remove(@PathVariable("id") String id) {
		FormEntity formEntity = formService.getById(id);
		if (StatusCode.FORM_EXTERNAL_PARAMETER.getCode().equals(formEntity.getPlace())){
			return R.fail("外部参数表单不能被删除");
		}
		boolean flag = formService.removeById(id);
		return flag? R.success("删除成功"): R.fail("删除失败");
	}

	@GetMapping("/list")
	@ApiOperation("表单列表-下拉列表")
	public R remove() {
		List<FormEntity> list = formService.list();
		list = list.stream().filter(x -> !x.getPlace().equals(StatusCode.FORM_EXTERNAL_PARAMETER.getCode())).collect(Collectors.toList());
		return R.data(list);
	}

	@ApiOperation("表单外部参数修改")
	@PostMapping("/updateExternalParameter")
	public R updateExternalParameter(@RequestBody JSONObject data,@RequestParam String place){
		boolean flag =formService.updateExternalParameter(data,place);
		return flag? R.success("修改成功"): R.fail("修改失败");
	}

	@ApiOperation("表单外部参数查询")
	@PostMapping("/selectExternalParameter")
	public R selectExternalParameter(@RequestParam String place){
		FormEntity formEntity = formService.findByPlace(place);
		return R.data(formEntity.getExternalParameter());
	}
}

